<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-left">
        <div class="welcome-text">
          <h2>欢迎加入</h2>
          <h1>邻里优选</h1>
          <p>便捷、安全、优质的社区团购平台</p>
        </div>
      </div>
      <div class="register-right">
        <div class="register-form-container">
          <h2>用户注册</h2>
          <p class="sub-title">创建您的账号，开始使用系统</p>

          <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                prefix-icon="el-icon-user"
                placeholder="请输入用户名">
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="请输入密码">
              </el-input>
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="请确认密码">
              </el-input>
            </el-form-item>

            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                prefix-icon="el-icon-mobile-phone"
                placeholder="请输入手机号">
              </el-input>
            </el-form-item>

            <el-form-item prop="address" v-if="registerForm.role === 'leader'">
              <el-input
                v-model="registerForm.address"
                prefix-icon="el-icon-location"
                placeholder="请输入配送地址">
              </el-input>
            </el-form-item>

            <el-form-item prop="name" v-if="registerForm.role === 'leader'">
              <el-input
                v-model="registerForm.name"
                prefix-icon="el-icon-user"
                placeholder="请输入团长姓名">
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-radio v-model="registerForm.role" label="leader">注册成为团长</el-radio>
            </el-form-item>

            <el-form-item>
              <div class="role-tip">
                <el-alert
                  title="注册成为团长后，您将能够创建自己的团购点"
                  type="info"
                  :closable="false"
                  show-icon>
                </el-alert>
                <p class="tip-text">注意：管理员账号由系统管理员创建，无法自行注册</p>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="register-button"
                :loading="loading"
                @click="handleRegister">
                注 册
              </el-button>
            </el-form-item>

            <div class="register-tips">
              <span>已有账号？</span>
              <router-link to="/login">立即登录</router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addUser } from '@/api/user'
import { addLeader, registerLeader } from '@/api/leader'
import request from '@/utils/request'

export default {
  name: 'Register',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        role: 'leader', // 默认注册为团长
        name: '',
        address: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入团长姓名', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入配送地址', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    // 检查手机号是否已被注册
    async checkPhoneExists(phone) {
      try {
        const response = await request({
          url: '/user/check-phone',
          method: 'get',
          params: { phone }
        })
        return response.data
      } catch (error) {
        console.error('检查手机号失败:', error)
        return true // 检查失败时默认为存在，以防止错误注册
      }
    },
    
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;

          if (this.registerForm.role === 'leader') {
            // 团长注册，使用新的合并接口
            const registerData = {
              username: this.registerForm.username,
              password: this.registerForm.password,
              phone: this.registerForm.phone,
              name: this.registerForm.name,
              address: this.registerForm.address
            };

            registerLeader(registerData)
              .then(() => {
                this.$message({
                  message: '注册成功，请登录',
                  type: 'success'
                });
                // 注册成功后跳转到登录页
                this.$router.push('/login');
              })
              .catch(error => {
                console.log('注册失败:', error);
                // 检查错误信息
                if (error.response && error.response.data) {
                  const errorMsg = error.response.data.message || '';
                  if (errorMsg.includes('手机号已被注册') || errorMsg.includes('手机号已存在') || errorMsg.includes('idx_phone')) {
                    this.$message.error('该手机号已被注册，请更换手机号或直接登录');
                  } else if (errorMsg.includes('用户名已存在')) {
                    this.$message.error('该用户名已被使用，请更换用户名');
                  } else {
                    this.$message.error('注册失败: ' + errorMsg);
                  }
                } else {
                  this.$message.error('注册失败，请稍后再试');
                }
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            // 普通用户注册
            const userData = {
              username: this.registerForm.username,
              password: this.registerForm.password,
              phone: this.registerForm.phone,
              role: this.registerForm.role,
              status: 1
            };

            addUser(userData)
              .then(() => {
                this.$message({
                  message: '注册成功，请登录',
                  type: 'success'
                });
                // 注册成功后跳转到登录页
                this.$router.push('/login');
              })
              .catch(error => {
                console.log('注册失败:', error);
                // 检查错误信息
                if (error.response && error.response.data) {
                  const errorMsg = error.response.data.message || '';
                  if (errorMsg.includes('手机号已被注册') || errorMsg.includes('手机号已存在') || errorMsg.includes('idx_phone')) {
                    this.$message.error('该手机号已被注册，请更换手机号或直接登录');
                  } else if (errorMsg.includes('用户名已存在')) {
                    this.$message.error('该用户名已被使用，请更换用户名');
                  } else {
                    this.$message.error('注册失败: ' + errorMsg);
                  }
                } else {
                  this.$message.error('注册失败，请稍后再试');
                }
              })
              .finally(() => {
                this.loading = false;
              });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;

  .register-box {
    width: 900px;
    height: 800px;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: hidden;

    .register-left {
      width: 50%;
      background: linear-gradient(135deg, #42b0ff, #4262ff);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      padding: 40px;

      .welcome-text {
        h1 {
          font-size: 32px;
          margin: 10px 0;
        }

        h2 {
          font-size: 24px;
          font-weight: normal;
        }

        p {
          margin-top: 20px;
          opacity: 0.8;
        }
      }
    }

    .register-right {
      width: 50%;
      background-color: white;
      padding: 40px;
      display: flex;
      align-items: center;

      .register-form-container {
        width: 100%;

        h2 {
          font-size: 24px;
          color: #333;
          margin-bottom: 10px;
        }

        .sub-title {
          color: #999;
          margin-bottom: 30px;
        }

        .register-form {
          .role-tip {
            margin-bottom: 15px;

            .tip-text {
              font-size: 12px;
              color: #f56c6c;
              margin-top: 8px;
              padding-left: 5px;
            }
          }

          .register-button {
            width: 100%;
            height: 40px;
            border-radius: 20px;
            font-size: 16px;
          }

          .register-tips {
            text-align: center;
            margin-top: 20px;
            color: #999;

            a {
              color: #4262ff;
              text-decoration: none;

              &:hover {
                text-decoration: underline;
              }
            }
          }
        }
      }
    }
  }
}
</style>
